package com.example.apple.startproject_126mjx.model;

import com.example.apple.startproject_126mjx.bean.WeatherResult;
import com.example.apple.startproject_126mjx.iface.WeatherIface;
import com.example.apple.startproject_126mjx.iface.WeatherListener;
import com.example.apple.startproject_126mjx.service.Weatherservice;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Apple on 2017/3/28.
 */

public class WeatherModel implements WeatherIface{
    private Retrofit retrofit;
    private  String BASEURL="http://www.weather.com.cn/";
    public WeatherModel() {
        //retrofit 实例化3-1
        retrofit=new Retrofit.Builder().baseUrl(BASEURL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    @Override
    public void getWeather(String cityno, final WeatherListener listener) {
        System.out.println("----WeatherModel-getWeather");
        //Retrofit 接口使用3-2
        Weatherservice weatherservice=retrofit.create(Weatherservice.class);
        Call<WeatherResult> call=weatherservice.getResult(cityno);
        //Retrofit 接口使用3-3
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                System.out.println("----WeatherModel-onResponse");
                if(response.isSuccessful()&&response.body()!=null)
                    listener.onResponse(response.body().getWeatherinfo());
                else
                    listener.onFail("onResponse error");
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listener.onFail(t.toString());
            }
        });
    }
}
